package com.itheima.order.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.order.client.GoodsClient;
import com.itheima.order.client.UserClient;
import com.itheima.order.mapper.OrderMapper;
import com.itheima.order.pojo.Address;
import com.itheima.order.pojo.Goods;
import com.itheima.order.pojo.Order;
import com.itheima.order.service.OrderService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Result getSubmitInfo(Long goodId) {
        List<Address> addressList = userClient.findByUsername("zhubajie");

        Result goodsResult = goodsClient.findById(goodId);

        Object data = goodsResult.getData();
        Goods goods = JSON.parseObject(JSONObject.toJSONString(data, true), Goods.class);

        Map map = new HashMap<>();

        map.put("addressList", addressList);
        map.put("goods", goods);

        return new Result(true, StatusCode.OK, null, map);
    }

    @Override
    public Result submitOrder(Order order) {

        if (order == null && order.getGoodId() == null) {
            return new Result(false, StatusCode.ERROR, "订单信息错误", null);
        }

        Result buyResult = goodsClient.buy(order.getGoodId(), 1);
        if (buyResult.isFlag()) {

            order.setStatus("1");
            java.util.Date date = new java.util.Date();
            order.setCreateTime(new Date(date.getTime()));
            order.setUpdateTime(new Date(date.getTime()));
            order.setUserId("zhubajie");
            this.orderMapper.insert(order);
            return new Result(true, StatusCode.OK, "创建订单成功！", String.valueOf(order.getOrderId()));

        }

        return buyResult;
    }
}
